package com.tuyue.police.biz.impl;

import com.tuyue.police.biz.ISmsBiz;
import com.tuyue.police.config.MsmConfig;
import com.tuyue.police.enums.ResultEnum;
import com.tuyue.police.exception.MyException;
import com.tuyue.police.redis.RedisService;
import com.tuyue.police.util.ToosUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/3/19.
 * @Modified By:
 */
@Service
public class SmsBizImpl implements ISmsBiz{

    @Autowired
    private MsmConfig msmConfig;

    @Autowired
    private RedisService redisService;
    @Autowired
    private MsmConfig config;
    @Override
    public boolean sendSms( String phone) {
        //获取随机数
        String random = ToosUtil.getRandom();
        //发送短信
//        Element element = dispatchMsg(phone, "您的验证码是："+random+"。请不要把验证码泄露给其他人。");
//        int code = Integer.parseInt(element.elementText("code"));
//        if (code!=2) {
//            throw new MyException(code,element.elementText("msg"));
//        }
        //保存redis
        redisService.set(config.getSmsprefix()+phone,random,180000);
        return true;
    }

    @Override
    public boolean verifySms( String phone, String code) {
        String redisCode = (String) redisService.get(config.getSmsprefix() + phone);
        if (StringUtils.isEmpty(redisCode)) {
            throw new MyException(ResultEnum.SMS_CODEPAST);
        }
        return redisCode.equals(code);
    }



    /**
     * 给一个人发送单条短信
     * @param mobile 手机号
     * @param code  短信内容
     */
    public Element dispatchMsg(String mobile, String code){

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(msmConfig.getSmsUrl());

        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        String content = new String(code);
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", msmConfig.getAccount()),
                new NameValuePair("password", msmConfig.getPassword()), 			//密码可以使用明文密码或使用32位MD5加密
                new NameValuePair("mobile", mobile),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult =method.getResponseBodyAsString();
            Document doc = DocumentHelper.parseText(SubmitResult);
            return doc.getRootElement();
        } catch (Exception e) {
            throw new MyException(ResultEnum.SMS_SERVERERROR);
        }


    }
}
